home *** CD-ROM | disk | FTP | other *** search
/ CU Amiga Super CD-ROM 13 / CU Amiga Magazine's Super CD-ROM 13 (1997)(EMAP Images)(GB)(Track 1 of 2)[!][issue 1997-08].iso / CUCD / Graphics / Ghostscript / src / jpeg-6a / wrjpgcom.c < prev    next >
C/C++ Source or Header  |  1995-11-15  |  16KB  |  576 lines

  1. /*
  2.  * wrjpgcom.c
  3.  *
  4.  * Copyright (C) 1994-1995, Thomas G. Lane.
  5.  * This file is part of the Independent JPEG Group's software.
  6.  * For conditions of distribution and use, see the accompanying README file.
  7.  *
  8.  * This file contains a very simple stand-alone application that inserts
  9.  * user-supplied text as a COM (comment) marker in a JFIF file.
  10.  * This may be useful as an example of the minimum logic needed to parse
  11.  * JPEG markers.
  12.  */
  13.  
  14. #define JPEG_CJPEG_DJPEG    /* to get the command-line config symbols */
  15. #include "jinclude.h"        /* get auto-config symbols, <stdio.h> */
  16.  
  17. #ifndef HAVE_STDLIB_H        /* <stdlib.h> should declare malloc() */
  18. extern void * malloc ();
  19. #endif
  20. #include <ctype.h>        /* to declare isupper(), tolower() */
  21. #ifdef USE_SETMODE
  22. #include <fcntl.h>        /* to declare setmode()'s parameter macros */
  23. /* If you have setmode() but not <io.h>, just delete this line: */
  24. #include <io.h>            /* to declare setmode() */
  25. #endif
  26.  
  27. #ifdef USE_CCOMMAND        /* command-line reader for Macintosh */
  28. #ifdef __MWERKS__
  29. #include <SIOUX.h>              /* Metrowerks needs this */
  30. #include <console.h>        /* ... and this */
  31. #endif
  32. #ifdef THINK_C
  33. #include <console.h>        /* Think declares it here */
  34. #endif
  35. #endif
  36.  
  37. #ifdef DONT_USE_B_MODE        /* define mode parameters for fopen() */
  38. #define READ_BINARY    "r"
  39. #define WRITE_BINARY    "w"
  40. #else
  41. #define READ_BINARY    "rb"
  42. #define WRITE_BINARY    "wb"
  43. #endif
  44.  
  45. #ifndef EXIT_FAILURE        /* define exit() codes if not provided */
  46. #define EXIT_FAILURE  1
  47. #endif
  48. #ifndef EXIT_SUCCESS
  49. #ifdef VMS
  50. #define EXIT_SUCCESS  1        /* VMS is very nonstandard */
  51. #else
  52. #define EXIT_SUCCESS  0
  53. #endif
  54. #endif
  55.  
  56. /* Reduce this value if your malloc() can't allocate blocks up to 64K.
  57.  * On DOS, compiling in large model is usually a better solution.
  58.  */
  59.  
  60. #ifndef MAX_COM_LENGTH
  61. #define MAX_COM_LENGTH 65000    /* must be < 65534 in any case */
  62. #endif
  63.  
  64.  
  65. /*
  66.  * These macros are used to read the input file and write the output file.
  67.  * To reuse this code in another application, you might need to change these.
  68.  */
  69.  
  70. static FILE * infile;        /* input JPEG file */
  71.  
  72. /* Return next input byte, or EOF if no more */
  73. #define NEXTBYTE()  getc(infile)
  74.  
  75. static FILE * outfile;        /* output JPEG file */
  76.  
  77. /* Emit an output byte */
  78. #define PUTBYTE(x)  putc((x), outfile)
  79.  
  80.  
  81. /* Error exit handler */
  82. #define ERREXIT(msg)  (fprintf(stderr, "%s\n", msg), exit(EXIT_FAILURE))
  83.  
  84.  
  85. /* Read one byte, testing for EOF */
  86. static int
  87. read_1_byte (void)
  88. {
  89.   int c;
  90.  
  91.   c = NEXTBYTE();
  92.   if (c == EOF)
  93.     ERREXIT("Premature EOF in JPEG file");
  94.   return c;
  95. }
  96.  
  97. /* Read 2 bytes, convert to unsigned int */
  98. /* All 2-byte quantities in JPEG markers are MSB first */
  99. static unsigned int
  100. read_2_bytes (void)
  101. {
  102.   int c1, c2;
  103.  
  104.   c1 = NEXTBYTE();
  105.   if (c1 == EOF)
  106.     ERREXIT("Premature EOF in JPEG file");
  107.   c2 = NEXTBYTE();
  108.   if (c2 == EOF)
  109.     ERREXIT("Premature EOF in JPEG file");
  110.   return (((unsigned int) c1) << 8) + ((unsigned int) c2);
  111. }
  112.  
  113.  
  114. /* Routines to write data to output file */
  115.  
  116. static void
  117. write_1_byte (int c)
  118. {
  119.   PUTBYTE(c);
  120. }
  121.  
  122. static void
  123. write_2_bytes (unsigned int val)
  124. {
  125.   PUTBYTE((val >> 8) & 0xFF);
  126.   PUTBYTE(val & 0xFF);
  127. }
  128.  
  129. static void
  130. write_marker (int marker)
  131. {
  132.   PUTBYTE(0xFF);
  133.   PUTBYTE(marker);
  134. }
  135.  
  136. static void
  137. copy_rest_of_file (void)
  138. {
  139.   int c;
  140.  
  141.   while ((c = NEXTBYTE()) != EOF)
  142.     PUTBYTE(c);
  143. }
  144.  
  145.  
  146. /*
  147.  * JPEG markers consist of one or more 0xFF bytes, followed by a marker
  148.  * code byte (which is not an FF).  Here are the marker codes of interest
  149.  * in this program.  (See jdmarker.c for a more complete list.)
  150.  */
  151.  
  152. #define M_SOF0  0xC0        /* Start Of Frame N */
  153. #define M_SOF1  0xC1        /* N indicates which compression process */
  154. #define M_SOF2  0xC2        /* Only SOF0-SOF2 are now in common use */
  155. #define M_SOF3  0xC3
  156. #define M_SOF5  0xC5        /* NB: codes C4 and CC are NOT SOF markers */
  157. #define M_SOF6  0xC6
  158. #define M_SOF7  0xC7
  159. #define M_SOF9  0xC9
  160. #define M_SOF10 0xCA
  161. #define M_SOF11 0xCB
  162. #define M_SOF13 0xCD
  163. #define M_SOF14 0xCE
  164. #define M_SOF15 0xCF
  165. #define M_SOI   0xD8        /* Start Of Image (beginning of datastream) */
  166. #define M_EOI   0xD9        /* End Of Image (end of datastream) */
  167. #define M_SOS   0xDA        /* Start Of Scan (begins compressed data) */
  168. #define M_COM   0xFE        /* COMment */
  169.  
  170.  
  171. /*
  172.  * Find the next JPEG marker and return its marker code.
  173.  * We expect at least one FF byte, possibly more if the compressor used FFs
  174.  * to pad the file.  (Padding FFs will NOT be replicated in the output file.)
  175.  * There could also be non-FF garbage between markers.  The treatment of such
  176.  * garbage is unspecified; we choose to skip over it but emit a warning msg.
  177.  * NB: this routine must not be used after seeing SOS marker, since it will
  178.  * not deal correctly with FF/00 sequences in the compressed image data...
  179.  */
  180.  
  181. static int
  182. next_marker (void)
  183. {
  184.   int c;
  185.   int discarded_bytes = 0;
  186.  
  187.   /* Find 0xFF byte; count and skip any non-FFs. */
  188.   c = read_1_byte();
  189.   while (c != 0xFF) {
  190.     discarded_bytes++;
  191.     c = read_1_byte();
  192.   }
  193.   /* Get marker code byte, swallowing any duplicate FF bytes.  Extra FFs
  194.    * are legal as pad bytes, so don't count them in discarded_bytes.
  195.    */
  196.   do {
  197.     c = read_1_byte();
  198.   } while (c == 0xFF);
  199.  
  200.   if (discarded_bytes != 0) {
  201.     fprintf(stderr, "Warning: garbage data found in JPEG file\n");
  202.   }
  203.  
  204.   return c;
  205. }
  206.  
  207.  
  208. /*
  209.  * Read the initial marker, which should be SOI.
  210.  * For a JFIF file, the first two bytes of the file should be literally
  211.  * 0xFF M_SOI.  To be more general, we could use next_marker, but if the
  212.  * input file weren't actually JPEG at all, next_marker might read the whole
  213.  * file and then return a misleading error message...
  214.  */
  215.  
  216. static int
  217. first_marker (void)
  218. {
  219.   int c1, c2;
  220.  
  221.   c1 = NEXTBYTE();
  222.   c2 = NEXTBYTE();
  223.   if (c1 != 0xFF || c2 != M_SOI)
  224.     ERREXIT("Not a JPEG file");
  225.   return c2;
  226. }
  227.  
  228.  
  229. /*
  230.  * Most types of marker are followed by a variable-length parameter segment.
  231.  * This routine skips over the parameters for any marker we don't otherwise
  232.  * want to process.
  233.  * Note that we MUST skip the parameter segment explicitly in order not to
  234.  * be fooled by 0xFF bytes that might appear within the parameter segment;
  235.  * such bytes do NOT introduce new markers.
  236.  */
  237.  
  238. static void
  239. copy_variable (void)
  240. /* Copy an unknown or uninteresting variable-length marker */
  241. {
  242.   unsigned int length;
  243.  
  244.   /* Get the marker parameter length count */
  245.   length = read_2_bytes();
  246.   write_2_bytes(length);
  247.   /* Length includes itself, so must be at least 2 */
  248.   if (length < 2)
  249.     ERREXIT("Erroneous JPEG marker length");
  250.   length -= 2;
  251.   /* Skip over the remaining bytes */
  252.   while (length > 0) {
  253.     write_1_byte(read_1_byte());
  254.     length--;
  255.   }
  256. }
  257.  
  258. static void
  259. skip_variable (void)
  260. /* Skip over an unknown or uninteresting variable-length marker */
  261. {
  262.   unsigned int length;
  263.  
  264.   /* Get the marker parameter length count */
  265.   length = read_2_bytes();
  266.   /* Length includes itself, so must be at least 2 */
  267.   if (length < 2)
  268.     ERREXIT("Erroneous JPEG marker length");
  269.   length -= 2;
  270.   /* Skip over the remaining bytes */
  271.   while (length > 0) {
  272.     (void) read_1_byte();
  273.     length--;
  274.   }
  275. }
  276.  
  277.  
  278. /*
  279.  * Parse the marker stream until SOFn or EOI is seen;
  280.  * copy data to output, but discard COM markers unless keep_COM is true.
  281.  */
  282.  
  283. static int
  284. scan_JPEG_header (int keep_COM)
  285. {
  286.   int marker;
  287.  
  288.   /* Expect SOI at start of file */
  289.   if (first_marker() != M_SOI)
  290.     ERREXIT("Expected SOI marker first");
  291.   write_marker(M_SOI);
  292.  
  293.   /* Scan miscellaneous markers until we reach SOFn. */
  294.   for (;;) {
  295.     marker = next_marker();
  296.     switch (marker) {
  297.     case M_SOF0:        /* Baseline */
  298.     case M_SOF1:        /* Extended sequential, Huffman */
  299.     case M_SOF2:        /* Progressive, Huffman */
  300.     case M_SOF3:        /* Lossless, Huffman */
  301.     case M_SOF5:        /* Differential sequential, Huffman */
  302.     case M_SOF6:        /* Differential progressive, Huffman */
  303.     case M_SOF7:        /* Differential lossless, Huffman */
  304.     case M_SOF9:        /* Extended sequential, arithmetic */
  305.     case M_SOF10:        /* Progressive, arithmetic */
  306.     case M_SOF11:        /* Lossless, arithmetic */
  307.     case M_SOF13:        /* Differential sequential, arithmetic */
  308.     case M_SOF14:        /* Differential progressive, arithmetic */
  309.     case M_SOF15:        /* Differential lossless, arithmetic */
  310.       return marker;
  311.  
  312.     case M_SOS:            /* should not see compressed data before SOF */
  313.       ERREXIT("SOS without prior SOFn");
  314.       break;
  315.  
  316.     case M_EOI:            /* in case it's a tables-only JPEG stream */
  317.       return marker;
  318.  
  319.     case M_COM:            /* Existing COM: conditionally discard */
  320.       if (keep_COM) {
  321.     write_marker(marker);
  322.     copy_variable();
  323.       } else {
  324.     skip_variable();
  325.       }
  326.       break;
  327.  
  328.     default:            /* Anything else just gets copied */
  329.       write_marker(marker);
  330.       copy_variable();        /* we assume it has a parameter count... */
  331.       break;
  332.     }
  333.   } /* end loop */
  334. }
  335.  
  336.  
  337. /* Command line parsing code */
  338.  
  339. static const char * progname;    /* program name for error messages */
  340.  
  341.  
  342. static void
  343. usage (void)
  344. /* complain about bad command line */
  345. {
  346.   fprintf(stderr, "wrjpgcom inserts a textual comment in a JPEG file.\n");
  347.   fprintf(stderr, "You can add to or replace any existing comment(s).\n");
  348.  
  349.   fprintf(stderr, "Usage: %s [switches] ", progname);
  350. #ifdef TWO_FILE_COMMANDLINE
  351.   fprintf(stderr, "inputfile outputfile\n");
  352. #else
  353.   fprintf(stderr, "[inputfile]\n");
  354. #endif
  355.  
  356.   fprintf(stderr, "Switches (names may be abbreviated):\n");
  357.   fprintf(stderr, "  -replace         Delete any existing comments\n");
  358.   fprintf(stderr, "  -comment \"text\"  Insert comment with given text\n");
  359.   fprintf(stderr, "  -cfile name      Read comment from named file\n");
  360.   fprintf(stderr, "Notice that you must put quotes around the comment text\n");
  361.   fprintf(stderr, "when you use -comment.\n");
  362.   fprintf(stderr, "If you do not give either -comment or -cfile on the command line,\n");
  363.   fprintf(stderr, "then the comment text is read from standard input.\n");
  364.   fprintf(stderr, "It can be multiple lines, up to %u characters total.\n",
  365.       (unsigned int) MAX_COM_LENGTH);
  366. #ifndef TWO_FILE_COMMANDLINE
  367.   fprintf(stderr, "You must specify an input JPEG file name when supplying\n");
  368.   fprintf(stderr, "comment text from standard input.\n");
  369. #endif
  370.  
  371.   exit(EXIT_FAILURE);
  372. }
  373.  
  374.  
  375. static int
  376. keymatch (char * arg, const char * keyword, int minchars)
  377. /* Case-insensitive matching of (possibly abbreviated) keyword switches. */
  378. /* keyword is the constant keyword (must be lower case already), */
  379. /* minchars is length of minimum legal abbreviation. */
  380. {
  381.   register int ca, ck;
  382.   register int nmatched = 0;
  383.  
  384.   while ((ca = *arg++) != '\0') {
  385.     if ((ck = *keyword++) == '\0')
  386.       return 0;            /* arg longer than keyword, no good */
  387.     if (isupper(ca))        /* force arg to lcase (assume ck is already) */
  388.       ca = tolower(ca);
  389.     if (ca != ck)
  390.       return 0;            /* no good */
  391.     nmatched++;            /* count matched characters */
  392.   }
  393.   /* reached end of argument; fail if it's too short for unique abbrev */
  394.   if (nmatched < minchars)
  395.     return 0;
  396.   return 1;            /* A-OK */
  397. }
  398.  
  399.  
  400. /*
  401.  * The main program.
  402.  */
  403.  
  404. int
  405. main (int argc, char **argv)
  406. {
  407.   int argn;
  408.   char * arg;
  409.   int keep_COM = 1;
  410.   char * comment_arg = NULL;
  411.   FILE * comment_file = NULL;
  412.   unsigned int comment_length = 0;
  413.   int marker;
  414.  
  415.   /* On Mac, fetch a command line. */
  416. #ifdef USE_CCOMMAND
  417.   argc = ccommand(&argv);
  418. #endif
  419.  
  420.   progname = argv[0];
  421.   if (progname == NULL || progname[0] == 0)
  422.     progname = "wrjpgcom";    /* in case C library doesn't provide it */
  423.  
  424.   /* Parse switches, if any */
  425.   for (argn = 1; argn < argc; argn++) {
  426.     arg = argv[argn];
  427.     if (arg[0] != '-')
  428.       break;            /* not switch, must be file name */
  429.     arg++;            /* advance over '-' */
  430.     if (keymatch(arg, "replace", 1)) {
  431.       keep_COM = 0;
  432.     } else if (keymatch(arg, "cfile", 2)) {
  433.       if (++argn >= argc) usage();
  434.       if ((comment_file = fopen(argv[argn], "r")) == NULL) {
  435.     fprintf(stderr, "%s: can't open %s\n", progname, argv[argn]);
  436.     exit(EXIT_FAILURE);
  437.       }
  438.     } else if (keymatch(arg, "comment", 1)) {
  439.       if (++argn >= argc) usage();
  440.       comment_arg = argv[argn];
  441.       /* If the comment text starts with '"', then we are probably running
  442.        * under MS-DOG and must parse out the quoted string ourselves.  Sigh.
  443.        */
  444.       if (comment_arg[0] == '"') {
  445.     comment_arg = (char *) malloc((size_t) MAX_COM_LENGTH);
  446.     if (comment_arg == NULL)
  447.       ERREXIT("Insufficient memory");
  448.     strcpy(comment_arg, argv[argn]+1);
  449.     for (;;) {
  450.       comment_length = strlen(comment_arg);
  451.       if (comment_length > 0 && comment_arg[comment_length-1] == '"') {
  452.         comment_arg[comment_length-1] = '\0'; /* zap terminating quote */
  453.         break;
  454.       }
  455.       if (++argn >= argc)
  456.         ERREXIT("Missing ending quote mark");
  457.       strcat(comment_arg, " ");
  458.       strcat(comment_arg, argv[argn]);
  459.     }
  460.       }
  461.       comment_length = strlen(comment_arg);
  462.     } else
  463.       usage();
  464.   }
  465.  
  466.   /* Cannot use both -comment and -cfile. */
  467.   if (comment_arg != NULL && comment_file != NULL)
  468.     usage();
  469.   /* If there is neither -comment nor -cfile, we will read the comment text
  470.    * from stdin; in this case there MUST be an input JPEG file name.
  471.    */
  472.   if (comment_arg == NULL && comment_file == NULL && argn >= argc)
  473.     usage();
  474.  
  475.   /* Open the input file. */
  476.   if (argn < argc) {
  477.     if ((infile = fopen(argv[argn], READ_BINARY)) == NULL) {
  478.       fprintf(stderr, "%s: can't open %s\n", progname, argv[argn]);
  479.       exit(EXIT_FAILURE);
  480.     }
  481.   } else {
  482.     /* default input file is stdin */
  483. #ifdef USE_SETMODE        /* need to hack file mode? */
  484.     setmode(fileno(stdin), O_BINARY);
  485. #endif
  486. #ifdef USE_FDOPEN        /* need to re-open in binary mode? */
  487.     if ((infile = fdopen(fileno(stdin), READ_BINARY)) == NULL) {
  488.       fprintf(stderr, "%s: can't open stdin\n", progname);
  489.       exit(EXIT_FAILURE);
  490.     }
  491. #else
  492.     infile = stdin;
  493. #endif
  494.   }
  495.  
  496.   /* Open the output file. */
  497. #ifdef TWO_FILE_COMMANDLINE
  498.   /* Must have explicit output file name */
  499.   if (argn != argc-2) {
  500.     fprintf(stderr, "%s: must name one input and one output file\n",
  501.         progname);
  502.     usage();
  503.   }
  504.   if ((outfile = fopen(argv[argn+1], WRITE_BINARY)) == NULL) {
  505.     fprintf(stderr, "%s: can't open %s\n", progname, argv[argn+1]);
  506.     exit(EXIT_FAILURE);
  507.   }
  508. #else
  509.   /* Unix style: expect zero or one file name */
  510.   if (argn < argc-1) {
  511.     fprintf(stderr, "%s: only one input file\n", progname);
  512.     usage();
  513.   }
  514.   /* default output file is stdout */
  515. #ifdef USE_SETMODE        /* need to hack file mode? */
  516.   setmode(fileno(stdout), O_BINARY);
  517. #endif
  518. #ifdef USE_FDOPEN        /* need to re-open in binary mode? */
  519.   if ((outfile = fdopen(fileno(stdout), WRITE_BINARY)) == NULL) {
  520.     fprintf(stderr, "%s: can't open stdout\n", progname);
  521.     exit(EXIT_FAILURE);
  522.   }
  523. #else
  524.   outfile = stdout;
  525. #endif
  526. #endif /* TWO_FILE_COMMANDLINE */
  527.  
  528.   /* Collect comment text from comment_file or stdin, if necessary */
  529.   if (comment_arg == NULL) {
  530.     FILE * src_file;
  531.     int c;
  532.  
  533.     comment_arg = (char *) malloc((size_t) MAX_COM_LENGTH);
  534.     if (comment_arg == NULL)
  535.       ERREXIT("Insufficient memory");
  536.     comment_length = 0;
  537.     src_file = (comment_file != NULL ? comment_file : stdin);
  538.     while ((c = getc(src_file)) != EOF) {
  539.       if (comment_length >= (unsigned int) MAX_COM_LENGTH) {
  540.     fprintf(stderr, "Comment text may not exceed %u bytes\n",
  541.         (unsigned int) MAX_COM_LENGTH);
  542.     exit(EXIT_FAILURE);
  543.       }
  544.       comment_arg[comment_length++] = (char) c;
  545.     }
  546.     if (comment_file != NULL)
  547.       fclose(comment_file);
  548.   }
  549.  
  550.   /* Copy JPEG headers until SOFn marker;
  551.    * we will insert the new comment marker just before SOFn.
  552.    * This (a) causes the new comment to appear after, rather than before,
  553.    * existing comments; and (b) ensures that comments come after any JFIF
  554.    * or JFXX markers, as required by the JFIF specification.
  555.    */
  556.   marker = scan_JPEG_header(keep_COM);
  557.   /* Insert the new COM marker, but only if nonempty text has been supplied */
  558.   if (comment_length > 0) {
  559.     write_marker(M_COM);
  560.     write_2_bytes(comment_length + 2);
  561.     while (comment_length > 0) {
  562.       write_1_byte(*comment_arg++);
  563.       comment_length--;
  564.     }
  565.   }
  566.   /* Duplicate the remainder of the source file.
  567.    * Note that any COM markers occuring after SOF will not be touched.
  568.    */
  569.   write_marker(marker);
  570.   copy_rest_of_file();
  571.  
  572.   /* All done. */
  573.   exit(EXIT_SUCCESS);
  574.   return 0;            /* suppress no-return-value warnings */
  575. }
  576.